import os
import cv2
import math

def getInfo(videopath):
    video = cv2.VideoCapture(videopath)
    fps = video.get(cv2.CAP_PROP_FPS)
    total_s = video.get(cv2.CAP_PROP_FRAME_COUNT)
    width = video.get(cv2.CAP_PROP_FRAME_WIDTH)
    height = video.get(cv2.CAP_PROP_FRAME_HEIGHT)
    return {'fps':math.ceil(fps),'all_frame':total_s,'width':width,'height':height}


# v=r'D:\Q\temp\A.mp4'
# info=getInfo(v)
# print(info)

def convertSequence(videopath,sdir):
    """

    :param videopath: 输入视频路径
    :param spath: 输出序列目录
    :return:
    """
    if not os.path.exists(sdir):
        os.makedirs(sdir)
    video = cv2.VideoCapture(videopath)
    fps = video.get(cv2.CAP_PROP_FPS)
    total_s = video.get(cv2.CAP_PROP_FRAME_COUNT)
    vc = cv2.VideoCapture(videopath)
    c = 1
    if vc.isOpened():
        rval, frame = vc.read()
    else:
        rval = False
    try:
        while rval:
            rval, frame = vc.read()
            outpath=os.path.join(sdir,str(c)+'.png')
            cv2.imwrite(outpath, frame)
            c = c + 1
            # if c==total_s:
            #     print(c)
            #     break
            cv2.waitKey(1)
    except Exception as convertSequence_ERR:
        print('convertSequence_ERR:',c,convertSequence_ERR)
    finally:
        vc.release()
    return {'fps': math.ceil(fps), 'all_frame': total_s,'sdir':sdir}

# outdir=r'D:\Q\TimeLineOut\我的第一个项目\序列'
# info=convertSequence(v,outdir)

# print(info)


##序列转mp4


import numpy as np

# path = '需要调用的图片路径 例如：C:/picture/'
# filelist = os.listdir(path)
#
fps = 24 #视频每秒24帧
size = (640, 480) #需要转为视频的图片的尺寸
# #可以使用cv2.resize()进行修改


# fourcc = cv2.VideoWriter_fourcc(*'mp4v')
fourcc =cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
vw = cv2.VideoWriter('a.mp4', fourcc, fps, size)

images_path=r'D:\Q\TimeLineOut\myFirstProject\imgs'
images_list=[os.path.join(images_path,n) for n in os.listdir(images_path)]
for img in images_list:
    i = cv2.imread(img)
    vw.write(i)

# video = cv2.VideoWriter("VideoTest1.avi", cv2.VideoWriter_fourcc('I', '4', '2', '0'), fps, size)
# #视频保存在当前目录下
#
# for item in filelist:
#     if item.endswith('.png'):
#     #找到路径中所有后缀名为.png的文件，可以更换为.jpg或其它
#         item = path + item
#         img = cv2.imread(item)
#         video.write(img)

vw.release()
cv2.destroyAllWindows()